"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 主节点挂掉，备机failover，查询集群状态,看主备是否一致
Create At   : 2020/07/23
@zou_jialiang0505328126
Description :
    1.主机创建表并插入数据
    2.在另外两备机查询该表
    3.kill主机进程
    4.其中一备机执行主备切换
    5.查询集群状态
    6.在主机创建表
    7.在另外一备机查询
Expect      :    
History     :   
    modified:2021/02/26 by @wan005:build增加等待时间,防止build超时
"""
import unittest
from yat.test import Node
import time

from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()
commonshpri = CommonSH('PrimaryDbUser')
commonshsta1 = CommonSH('Standby1DbUser')
commonshsta2 = CommonSH('Standby2DbUser')


class ModifyPidFile(unittest.TestCase):
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        self.constant = Constant()
        logger.info('------------Opengauss_Reliability_Dbsys_Case131.py start------------')

    def test_modify_pidfile(self):
        try:
            logger.info("-----------primary create table &insert data-----------")
            result = commonshpri.executDbSql(
                'create table test_table55(id int,name varchar(20));')
            logger.info(result)
            self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result)
            result = commonshpri.executDbSql(
                'insert into test_table55 values(1,\'aaa\');'
                'insert into test_table55 values(2,\'aaa\');')
            self.assertIn('INSERT', result)

            logger.info("-----------check data consistency-----------")
            flag = commonshsta1.check_data_consistency()
            self.assertTrue(flag)
            flag = commonshsta2.check_data_consistency()
            self.assertTrue(flag)
            logger.info("-----------query data consistency-----------")
            result = commonshsta1.executDbSql('select count(*) from test_table55;')
            logger.info(result)
            self.assertTrue(result.find('2') > -1)
            result = commonshsta2.executDbSql('select count(*) from test_table55;')
            logger.info(result)
            self.assertTrue(result.find('2') > -1)
        finally:
            commonshpri.executDbSql('drop table test_table55')

        logger.info('--------------------kill primary pid-------------------------')
        getPidCmd = 'lsof -i:{port}'.replace('{port}', self.dbPrimaryRootNode.db_port)
        pidMsg = self.dbPrimaryRootNode.sh(getPidCmd).result()
        pid = common.getPidFromCmd(str(pidMsg))
        self.dbPrimaryRootNode.sh('kill -9 ' + pid)

        logger.info('------------- standby1 failover----------------')
        result = commonshsta1.executeGsctl(
            'failover', self.constant.FAILOVER_SUCCESS_MSG)
        self.assertTrue(result)
        result = commonshsta1.exec_refresh_conf()
        self.assertTrue(result)

        logger.info('-------------check opengauss status-----------')
        result = commonshsta1.getDbClusterStatus('detail')
        self.assertEqual(result.count('Normal'), 2)

        logger.info("------standby1 create table &insert data-----")
        result = commonshsta1.executDbSql(
            'create table test_table5(id int,name varchar(20));')
        logger.info(result)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, result)
        result = commonshsta1.executDbSql(
            'insert into test_table5 values(1,\'aaa\');'
            'insert into test_table5 values(2,\'aaa\');')
        logger.info(result)
        self.assertIn('INSERT', result)

        logger.info("-----------check data consistency-----------")
        flag = commonshsta2.check_data_consistency()
        self.assertTrue(flag)
        logger.info("-----------query data consistency-----------")
        result = commonshsta2.executDbSql('select count(*) from test_table5;')
        logger.info(result)
        self.assertTrue(result.find('2') > -1)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info('------------drop table------------')
        result = commonshsta1.executDbSql('drop table test_table5')
        logger.info(result)
        logger.info('--------------build primary-----------------')
        result = commonshpri.buildStandby()
        logger.info(result)
        time.sleep(20)

        logger.info('-----------check opengauss status------------')
        commonshsta1.getDbClusterStatus('detail')

        logger.info('-----------switchover primary----------')
        result = commonshpri.executeGsctl(
            'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
        logger.info(result)
        result = commonshpri.exec_refresh_conf()
        logger.info(result)